<template>
  <view class="address-container">
    <!-- 地址列表 -->
    <view class="address-list" v-if="addressList.length > 0">
      <view 
        class="address-item" 
        v-for="(item, index) in addressList" 
        :key="index" 
        :class="{'slide-open': item.showActions, 'selected': selectedId === item.address_id}"
        @touchstart="touchStart($event, index)"
        @touchmove="touchMove($event, index)"
        @touchend="touchEnd($event, index)">
        <view class="address-content" @tap="selectAddress(item)">
          <view class="address-info">
            <view class="address-top">
              <text class="address-name">{{item.name}}</text>
              <text class="address-phone">{{item.phone}}</text>
              <view class="address-tag" v-if="item.is_default == 1">
                <text>默认</text>
              </view>
              <view class="address-tag home-tag" v-if="item.tag === 'home'">
                <text>家</text>
              </view>
              <view class="address-tag company-tag" v-if="item.tag === 'company'">
                <text>公司</text>
              </view>
              <view class="address-tag school-tag" v-if="item.tag === 'school'">
                <text>学校</text>
              </view>
              <view class="address-tag custom-tag" v-if="item.tag === 'custom'">
                <text>{{item.customTagText}}</text>
              </view>
            </view>
            <text class="address-detail">{{item.region.province}}{{item.region.city}}{{item.region.region}}{{item.detail}}</text>
          </view>
          <view class="address-right">
            <text class="arrow-right-small">›</text>
          </view>
        </view>
        <!-- 滑动操作区域 -->
        <view class="address-actions">
          <view class="action-btn edit-btn" @tap="editAddress(item)">
            <image class="action-icon" src="/static/icons/edit-white.png"></image>
            <text>编辑</text>
          </view>
          <view class="action-btn delete-btn" @tap="deleteAddress(item.address_id)">
            <image class="action-icon" src="/static/icons/delete-white.png"></image>
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空地址提示 -->
    <view class="empty-address" v-else>
      <image class="empty-icon" src="/static/icons/empty-address.png"></image>
      <text class="empty-text">您还没有添加收货地址</text>
      <text class="empty-subtitle">添加地址后，下次下单更便捷</text>
    </view>
    
    <!-- 添加新地址按钮 -->
    <view class="add-address-btn" @tap="addNewAddress">
      <text class="add-icon">+</text>
      <text class="add-text">新增收货地址</text>
    </view>
    
    <!-- 地址编辑弹窗 -->
    <view class="address-modal" v-if="showAddressModal">
      <view class="modal-mask" @tap="closeModal"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">{{isEdit ? '编辑地址' : '新增地址'}}</text>
          <text class="close-btn" @tap="closeModal">×</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">收货人</text>
          <input type="text" v-model="currentAddress.name" placeholder="请输入姓名" class="form-input" />
        </view>
        
        <view class="form-item">
          <text class="form-label">手机号码</text>
          <input type="number" v-model="currentAddress.phone" placeholder="请输入手机号码" class="form-input" maxlength="11" />
        </view>
        
        <view class="form-item">
          <text class="form-label">所在地区</text>
          <uni-data-picker 
            v-model="currentAddress.region_id" 
            :localdata="regionOption" 
            popup-title="请选择省/市/区" 
            :map="{ text: 'name', value: 'id' }" 
            @change="setRegion" 
            :clear-icon="false" />
        </view>
        
        <view class="form-item">
          <text class="form-label">详细地址</text>
          <textarea v-model="currentAddress.detail" placeholder="请输入详细地址，如街道、门牌号等" class="form-textarea" />
        </view>
        
        <view class="form-item">
          <text class="form-label">地址标签</text>
          <view class="tag-options">
            <view 
              class="tag-option" 
              :class="{'tag-active': currentAddress.tag === 'home'}" 
              @tap="selectTag('home')">
              <text>家</text>
            </view>
            <view 
              class="tag-option" 
              :class="{'tag-active': currentAddress.tag === 'company'}" 
              @tap="selectTag('company')">
              <text>公司</text>
            </view>
            <view 
              class="tag-option" 
              :class="{'tag-active': currentAddress.tag === 'school'}" 
              @tap="selectTag('school')">
              <text>学校</text>
            </view>
            <view 
              class="tag-option custom-tag" 
              :class="{'tag-active': currentAddress.tag === 'custom'}" 
              @tap="selectTag('custom')">
              <text>自定义</text>
            </view>
          </view>
          <input 
            v-if="currentAddress.tag === 'custom'" 
            type="text" 
            v-model="currentAddress.customTagText" 
            placeholder="请输入自定义标签" 
            class="form-input custom-tag-input" 
            maxlength="4" />
        </view>
        
        <view class="form-item switch-item">
          <text class="form-label">设为默认地址</text>
          <switch :checked="currentAddress.is_default == 1" @change="switchDefault" color="#5C8D69" />
        </view>
        
        <view class="form-btns">
          <view class="form-btn cancel-btn" @tap="closeModal">取消</view>
          <view class="form-btn confirm-btn" @tap="saveAddress">保存</view>
        </view>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <view class="confirm-modal" v-if="showDeleteModal">
      <view class="modal-mask" @tap="closeDeleteModal"></view>
      <view class="confirm-content">
        <text class="confirm-title">删除地址</text>
        <text class="confirm-text">确定要删除该收货地址吗？</text>
        <view class="confirm-btns">
          <view class="confirm-btn cancel-btn" @tap="closeDeleteModal">取消</view>
          <view class="confirm-btn delete-btn" @tap="confirmDelete">删除</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getRegionOption } from '../../api/public';
import { addAddressApi, addressListApi, delAddressApi, editAddressApi } from '../../api/user';
import { loading, hideloading, tip } from '../../utils';

export default {
  data() {
    return {
      selectedId: '',
      addressList: [],
      showAddressModal: false,
      showDeleteModal: false,
      isEdit: false,
      deleteId: null,
      currentAddress: {
        address_id: null,
        name: '',
        phone: '',
        province_id: '',
        city_id: '',
        region_id: '',
        detail: '',
        is_default: 0,
        tag: '',
        customTagText: '',
        region: {
          province: '',
          city: '',
          region: ''
        }
      },
      // 触摸滑动相关变量
      startX: 0,
      moveX: 0,
      isSelect: false,
      regionOption: []
    }
  },
  onLoad(options) {
    // 如果有传入的选中地址ID
    if (options.selectedId) {
      this.selectedId = options.selectedId;
    }
    
    this.isSelect = options.select ? true : false;
    
    // 获取地址列表和地区数据
    this.getAddressList();
    
    // 获取地区数据
    getRegionOption().then(res => {
      if (res) {
        this.regionOption = res;
        console.log('Region options loaded:', this.regionOption.length);
      }
    }).catch(err => {
      console.error('Failed to load region options:', err);
    });
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },
    
    // 获取地址列表
    getAddressList() {
      loading('加载中...');
      addressListApi().then((res) => {
        hideloading();
        if (res && res.list) {
          this.addressList = res.list.map(item => {
            return {
              ...item,
              showActions: false
            };
          });
          
          // 默认选中默认地址
          if (!this.selectedId && this.addressList.length > 0) {
            const defaultAddress = this.addressList.find(item => item.is_default == 1);
            if (defaultAddress) {
              this.selectedId = defaultAddress.address_id;
            } else {
              this.selectedId = this.addressList[0].address_id;
            }
          }
        }
      }).catch(err => {
        hideloading();
        tip('获取地址列表失败');
        console.error(err);
      });
    },
    
    // 地址选择
    selectAddress(item) {
      if (!this.isSelect) {
        return false;
      }
      
      // 关闭所有打开的滑动操作
      this.addressList.forEach(addr => {
        addr.showActions = false;
      });

      this.selectedId = item.address_id;

      // 将地址数据传回上一页
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];

      // 设置上一页的地址数据
      if (prevPage && prevPage.$vm) {
        prevPage.$vm.address = JSON.parse(JSON.stringify(item));
      }

      uni.navigateBack();
    },
    
    // 滑动操作相关方法
    touchStart(e, index) {
      // 关闭其他打开的滑动操作
      this.addressList.forEach((item, idx) => {
        if (idx !== index) {
          item.showActions = false;
        }
      });
      
      this.startX = e.touches[0].clientX;
    },
    
    touchMove(e, index) {
      this.moveX = e.touches[0].clientX;
      const distance = this.startX - this.moveX;
      
      // 只允许向左滑动显示操作按钮
      if (distance > 50) {
        this.addressList[index].showActions = true;
      } else if (distance < -50) {
        this.addressList[index].showActions = false;
      }
    },
    
    touchEnd(e, index) {
      this.startX = 0;
      this.moveX = 0;
    },
    
    // 地址操作相关方法
    addNewAddress() {
      this.isEdit = false;
      this.currentAddress = {
        address_id: null,
        name: '',
        phone: '',
        province_id: '',
        city_id: '',
        region_id: '',
        detail: '',
        is_default: 0,
        tag: '',
        customTagText: '',
        region: {
          province: '',
          city: '',
          region: ''
        }
      };
      this.showAddressModal = true;
    },
    
    editAddress(item) {
      this.isEdit = true;
      // 深拷贝确保不影响原数据
      this.currentAddress = JSON.parse(JSON.stringify(item));
      this.showAddressModal = true;
    },
    
    closeModal() {
      this.showAddressModal = false;
    },
    
    // 地区选择回调
    setRegion(e) {
      console.log('Region selected:', e);
      if (e && e.detail && e.detail.value) {
        const val = e.detail.value;
        
        // 确保有三级选择
        if (val.length >= 3) {
          this.currentAddress.province_id = val[0].value;
          this.currentAddress.city_id = val[1].value;
          this.currentAddress.region_id = val[2].value;
          
          // 更新地区名称以供显示
          this.currentAddress.region = {
            province: val[0].text,
            city: val[1].text,
            region: val[2].text
          };
          
          console.log('Region set:', this.currentAddress.region);
        } else {
          tip('请选择完整的省市区');
        }
      }
    },
    
    switchDefault(e) {
      this.currentAddress.is_default = e.detail.value ? 1 : 0;
    },
    
    selectTag(tag) {
      this.currentAddress.tag = tag;
      switch (tag) {
        case 'home':
          this.currentAddress.customTagText = '家';
          break;
        case 'company':
          this.currentAddress.customTagText = '公司';
          break;
        case 'school':
          this.currentAddress.customTagText = '学校';
          break;
        case 'custom':
          this.currentAddress.customTagText = '';
          break;
      }
    },
    
    saveAddress() {
      // 表单验证
      if (!this.currentAddress.name) {
        tip('请输入收货人姓名');
        return;
      }
      if (!this.currentAddress.phone) {
        tip('请输入手机号码');
        return;
      }
      if (!/^1\d{10}$/.test(this.currentAddress.phone)) {
        tip('手机号码格式不正确');
        return;
      }
      if (!this.currentAddress.province_id || !this.currentAddress.city_id || !this.currentAddress.region_id) {
        tip('请选择所在地区');
        return;
      }
      if (!this.currentAddress.detail) {
        tip('请输入详细地址');
        return;
      }
      
      // 自定义标签验证
      if (this.currentAddress.tag === 'custom' && !this.currentAddress.customTagText) {
        tip('请输入自定义标签');
        return;
      }
      
      loading('保存中...');
      
      // 构建请求参数
      const params = {
        name: this.currentAddress.name,
        phone: this.currentAddress.phone,
        province_id: this.currentAddress.province_id,
        city_id: this.currentAddress.city_id,
        region_id: this.currentAddress.region_id,
        detail: this.currentAddress.detail,
        is_default: this.currentAddress.is_default,
        tag: this.currentAddress.tag,
        customTagText: this.currentAddress.customTagText
      };
      
      if (this.isEdit) {
        // 编辑地址
        params.address_id = this.currentAddress.address_id;
        
        editAddressApi(params).then(res => {
          hideloading();
         
		  tip('修改成功', 'success');
		  this.getAddressList();
		  this.closeModal();
        }).catch(err => {
          hideloading();
          tip('修改失败');
          console.error(err);
        });
      } else {
		  
		  
        // 添加地址
        addAddressApi(params).then(res => {
			console.log(res);
          hideloading();
         
            tip('添加成功', 'success');
            this.getAddressList();
            this.closeModal();
        }).catch(err => {
          hideloading();
          tip('添加失败');
          console.error(err);
        });
      }
    },
    
    deleteAddress(id) {
      this.deleteId = id;
      this.showDeleteModal = true;
    },
    
    closeDeleteModal() {
      this.showDeleteModal = false;
      this.deleteId = null;
    },
    
    confirmDelete() {
      if (this.deleteId) {
        loading('删除中...');
        
        delAddressApi({
          address_id: this.deleteId
        }).then(res => {
			console.log(res);
          hideloading();
          
            tip('删除成功', 'success');
            this.getAddressList();
      
        }).catch(err => {
          hideloading();
          tip('删除失败');
          console.error(err);
        });
      }
      this.closeDeleteModal();
    }
  }
}
</script>

<style>
.address-container {
  background-color: #F8F5F0;
  /* 米白色背景 */
  min-height: 100vh;
  position: relative;
  padding-bottom: 120rpx;
}

/* 地址列表 */
.address-list {
  padding: 0 30rpx;
}

.address-item {
  position: relative;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  transform: translateX(0);
  transition: transform 0.3s;
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #FFFFFF;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 2;
  position: relative;
}

.slide-open .address-content {
  transform: translateX(-200rpx);
}

.address-item.selected .address-content {
  background-color: #F1EFE8;
  border-left: 6rpx solid #5C8D69;
}

.address-info {
  flex: 1;
  margin-right: 20rpx;
}

.address-top {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 15rpx;
}

.address-name {
  font-size: 30rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  font-weight: bold;
  margin-right: 20rpx;
}

.address-phone {
  font-size: 28rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
  margin-right: 20rpx;
}

.address-tag {
  background-color: #E8C872;
  /* 佛经黄 */
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  margin-right: 10rpx;
}

.home-tag {
  background-color: #5C8D69;
  /* 青瓷绿 */
}

.company-tag {
  background-color: #7B7FC9;
  /* 淡紫色 */
}

.school-tag {
  background-color: #E79B5E;
  /* 橙色 */
}

.custom-tag {
  background-color: #9C8679; /* 棕褐色 */
}

.address-tag text {
  font-size: 22rpx;
  color: #FFFFFF;
  font-family: "思源宋体", sans-serif;
}

.address-detail {
  font-size: 26rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  line-height: 1.5;
}

.address-right {
  display: flex;
  align-items: center;
}

.arrow-right-small {
  font-size: 32rpx;
  color: #8C7B68;
}

/* 滑动操作区域 */
.address-actions {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  display: flex;
  align-items: stretch;
  z-index: 1;
}

.action-btn {
  width: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background-color: #5C8D69;
  /* 青瓷绿 */
}

.delete-btn {
  background-color: #E76F51;
  /* 暖红色 */
}

.action-icon {
  width: 36rpx;
  height: 36rpx;
  margin-bottom: 6rpx;
}

.action-btn text {
  font-size: 22rpx;
  color: #FFFFFF;
  font-family: "思源宋体", sans-serif;
}

/* 空地址提示 */
.empty-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.empty-subtitle {
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

/* 添加新地址按钮 */
.add-address-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  height: 90rpx;
  background-color: #5C8D69;
  /* 青瓷绿 */
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(92, 141, 105, 0.3);
  z-index: 5;
}

.add-icon {
  font-size: 36rpx;
  color: #FFFFFF;
  margin-right: 10rpx;
}

.add-text {
  font-size: 30rpx;
  color: #FFFFFF;
  font-family: "思源宋体", sans-serif;
  letter-spacing: 2rpx;
}

/* 地址编辑弹窗 */
.address-modal,
.confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFFFFF;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  padding: 30rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 30rpx;
  border-bottom: 1px solid #EEEAE3;
  margin-bottom: 30rpx;
}

.modal-title {
  font-size: 32rpx;
  color: #5C4B3A;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
  font-weight: bold;
}

.close-btn {
  font-size: 40rpx;
  color: #8C7B68;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  margin-bottom: 15rpx;
  display: block;
}

.form-input {
  height: 80rpx;
  background-color: #F8F5F0;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
}

.form-textarea {
  height: 160rpx;
  background-color: #F8F5F0;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  width: 100%;
  box-sizing: border-box;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 地址标签样式 */
.tag-options {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.tag-option {
  padding: 8rpx 30rpx;
  background-color: #EEEAE3;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.tag-option text {
  font-size: 24rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
}

.tag-active {
  background-color: #5C8D69;
}

.tag-active text {
  color: #FFFFFF;
}

.custom-tag-input {
  margin-top: 10rpx;
}

.form-btns {
  display: flex;
  margin-top: 50rpx;
}

.form-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-family: "思源宋体", sans-serif;
}

.cancel-btn {
  background-color: #EEEAE3;
  color: #8C7B68;
  margin-right: 20rpx;
}

.confirm-btn {
  background-color: #5C8D69;
  /* 青瓷绿 */
  color: #FFFFFF;
}

/* 删除确认弹窗 */
.confirm-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 560rpx;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
}

.confirm-title {
  font-size: 32rpx;
  color: #5C4B3A;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.confirm-text {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  text-align: center;
  margin-bottom: 40rpx;
}

.confirm-btns {
  display: flex;
}

.confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-family: "思源宋体", sans-serif;
}

.delete-btn {
  background-color: #E76F51;
  /* 暖红色 */
  color: #FFFFFF;
}

/* 适配iPhone底部安全区域 */
.modal-content {
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
}

.add-address-btn {
  bottom: calc(30rpx + env(safe-area-inset-bottom));
}

/* 交互动效 */
@keyframes slideIn {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}

.modal-content {
  animation: slideIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.address-item {
  animation: fadeIn 0.3s ease-out;
}

.add-address-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.address-content:active {
  background-color: #F8F5F0;
}

.form-btn:active {
  opacity: 0.9;
}

.action-btn:active {
  opacity: 0.8;
}

.uni-data-tree {
  color: #5C4B3A;
  background: #F8F5F0;
}
</style>